"""
获取最近查询的历史
"""
from db.cache import get_cache, set_cache
from common.utils import init_item, empty


HISTORY_CACHE_KEY = 'query_history_cache_key'


def history():
    history_list = get_cache(HISTORY_CACHE_KEY, [])
    results = []
    for single_data in history_list:
        # 封装数据
        results.append(init_item(
            text=single_data,
            subtext='按tab键可再次搜索',
            completion=single_data
        ))
        pass
    return results
    pass


def remember_search(query_model):
    query_str = "%s %s" % (query_model.trigger, query_model.query_str)
    last_str = '' if empty(query_str.strip()) else query_str.strip()[-1]
    if last_str != '|':
        return
        pass
    history_list = get_cache(HISTORY_CACHE_KEY, [])
    # 将当前查询的记录放在最前
    new_history_list = [query_str]
    for h in history_list:
        if h != query_str:
            new_history_list.append(h)
    set_cache(HISTORY_CACHE_KEY, new_history_list)
    pass
